﻿using FullCoreDBModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Speech.AudioFormat;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;

namespace FullCoreWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ToolsController : ControllerBase
    {
        private string GetMD5(string str)
        {
            byte[] buffer = Encoding.Default.GetBytes(str); //将字符串解析成字节数组，随便按照哪种解析格式都行

            MD5 md5 = MD5.Create();  //使用MD5这个抽象类的Creat()方法创建一个虚拟的MD5类的对象。

            byte[] bufferNew = md5.ComputeHash(buffer); //使用MD5实例的ComputerHash()方法处理字节数组。

            string strNew = null;

            for (int i = 0; i < bufferNew.Length; i++)
            {

                strNew += bufferNew[i].ToString("x2");  //对bufferNew字节数组中的每个元素进行十六进制转换然后拼接成strNew字符串

            }
            return strNew;
        }
        [HttpGet]
        public CommonResult Text2Vocie(string text)
        {
            string fileName = GetMD5(text);
            string filePath = System.AppDomain.CurrentDomain.BaseDirectory + $"\\speech\\{fileName}.wav";
            try
            {
                if (text.Length > 65535)
                {
                    return new CommonResult() { Result = false };
                }


                if (System.IO.File.Exists(filePath))
                {

                }
                else
                {
                    using (SpeechSynthesizer synth = new SpeechSynthesizer())
                    {
                        synth.SetOutputToWaveFile(filePath, new SpeechAudioFormatInfo(32000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
                        PromptBuilder builder = new PromptBuilder();
                        builder.AppendText(text);
                        synth.Speak(builder);
                    }
                }
            }
            catch (Exception e)
            {
                return new CommonResult() { Result = false };
            }
            string file = $"\\speech\\{fileName}.wav";
            FileStream stream = new FileStream(filePath, FileMode.Open);
            string base64Str = "";
            using (BinaryReader binReader = new BinaryReader(stream))
            {
                byte[] bytes = binReader.ReadBytes(Convert.ToInt32(stream.Length));
                base64Str = Convert.ToBase64String(bytes);
            }
            return new CommonResult() { Result = true, ReturnData = base64Str };
        }
    }
}
